"use client";

import { useEffect, useState } from "react";
import { useParams } from "next/navigation";
import { Button } from "@/components/ui/button";
import { ChatInterface } from "@/components/chat/ChatInterface";
import { Message, ChatSession, MessageRole } from "@/types/chat";

// 模拟从API获取聊天数据
const fetchChatSession = async (id: string): Promise<ChatSession | null> => {
  // 这里应该是实际的API调用
  await new Promise((resolve) => setTimeout(resolve, 1000)); // 模拟网络延迟

  // 模拟数据
  const mockSession: ChatSession = {
    id,
    title: `聊天会话 ${id}`,
    messages: [
      {
        role: "system",
        content: "我是一个AI助手，可以帮助你回答问题。",
        timestamp: new Date(Date.now() - 3600000),
      },
      {
        role: "user",
        content: "你好，请介绍一下你自己。",
        timestamp: new Date(Date.now() - 3000000),
      },
      {
        role: "assistant",
        content: "你好！我是一个AI助手，基于大型语言模型开发。我可以回答问题、提供信息、参与对话等。有什么我可以帮助你的吗？",
        timestamp: new Date(Date.now() - 2400000),
      },
    ],
    createdAt: new Date(Date.now() - 3600000),
    updatedAt: new Date(Date.now() - 2400000),
  };

  return mockSession;
};

export default function ChatPage() {
  const params = useParams();
  const chatId = params.id as string;
  
  const [session, setSession] = useState<ChatSession | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    const loadChat = async () => {
      try {
        setLoading(true);
        const data = await fetchChatSession(chatId);
        setSession(data);
        setError(null);
      } catch (err) {
        console.error("加载聊天会话失败:", err);
        setError("无法加载聊天会话，请稍后再试");
      } finally {
        setLoading(false);
      }
    };

    loadChat();
  }, [chatId]);

  const handleSendMessage = async (content: string) => {
    // 这里应该是实际发送消息到API的逻辑
    await new Promise((resolve) => setTimeout(resolve, 1500)); // 模拟网络延迟
    
    // 模拟AI响应
    const aiResponse: Message = {
      role: "assistant",
      content: `这是对"${content}"的模拟回复。在实际应用中，这将是从API返回的响应。`,
      timestamp: new Date(),
    };
    
    // 更新会话状态
    if (session) {
      const userMessage: Message = {
        role: "user",
        content,
        timestamp: new Date()
      };
      
      const updatedSession: ChatSession = {
        ...session,
        messages: [...session.messages, userMessage, aiResponse],
        updatedAt: new Date(),
      };
      setSession(updatedSession);
    }
  };

  if (loading) {
    return (
      <div className="flex h-full items-center justify-center">
        <div className="h-8 w-8 animate-spin rounded-full border-4 border-blue-500 border-t-transparent"></div>
      </div>
    );
  }

  if (error || !session) {
    return (
      <div className="flex h-full flex-col items-center justify-center p-4">
        <div className="mb-4 text-xl font-semibold text-red-500">
          {error || "找不到聊天会话"}
        </div>
        <Button asChild>
          <a href="/chat">返回聊天列表</a>
        </Button>
      </div>
    );
  }

  return (
    <div className="flex h-full flex-col">
      <div className="border-b p-4 dark:border-gray-700">
        <h1 className="text-xl font-semibold">{session.title}</h1>
      </div>
      <div className="flex-1 overflow-hidden">
        <ChatInterface
          initialMessages={session.messages}
          onSendMessage={handleSendMessage}
        />
      </div>
    </div>
  );
} 